package com.harlaus.lucenedemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.harlaus.lucenedemo.entity.User;
import com.harlaus.lucenedemo.mapper.UserRepository;
import com.harlaus.lucenedemo.service.UserSolrService;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrOperations;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Service;

import javax.xml.datatype.Duration;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Service
public class UserSolrServiceImpl implements UserSolrService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SolrClient solrClient;

    @Autowired
    private SolrOperations solrOperations;

    @Override
    public Boolean addUserSolr(User user) {
        try {
            solrClient.addBean(user);
            solrClient.commit();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Boolean removeUserSolr(User user) {
        try {
            solrClient.deleteByQuery("*:*");
            solrClient.commit();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<User> queryUserSolr(User user) {
        SolrDocument document = null;
        SolrQuery query = new SolrQuery();
        query.setQuery("username:张三");
        List<User> users = null;
        try {
            QueryResponse queryResponse = solrClient.query(query, SolrRequest.METHOD.POST);
            SolrDocumentList results = queryResponse.getResults();
            String s = JSONObject.toJSONString(results);
            users = JSONObject.parseArray(s, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }
}
